package com.hmdp.utils;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.entity.Shop;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

@Component
@Slf4j
public class CacheClient {
    //通过构造函数注入
    private final StringRedisTemplate stringRedisTemplate;

    public CacheClient(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }
    public void set(String key, Object value, Long time, TimeUnit unit) {
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value), time, unit);
    }
    public void setWithLogicalExpire(String key, Object value, Long time, TimeUnit unit) {
        //封装逻辑过期
        RedisData redisData = new RedisData();
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));
        //写入redis
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
    }

    /**
     * 缓存穿透解决逻辑
     * @param id
     * @return
     */
    public <R,ID> R queryWithPassThrough(String keyPrefix,ID id, Class<R> type, Function<ID,R> dbFallback, Long time, TimeUnit unit) {
        //1.在redis中查询对象信息
        String s = stringRedisTemplate.opsForValue().get(keyPrefix + id);
        //2.判断对象是否存在
        if (StrUtil.isNotBlank(s)) {
            //3.对象存在，直接返回
            R r = JSONUtil.toBean(s, type);
            return r;
        }
        //判断是否命中空值
        if (s != null) {
            //4.对象不存在，返回错误
            return null;
        }
        //4.对象不存在，查询数据库
        R r= dbFallback.apply(id);
        //5.数据库中不存在，返回错误
        if (r == null) {
            //解决缓存穿透问题
            //1将空值写入redis
            stringRedisTemplate.opsForValue().set(keyPrefix+ id, "", time, unit);
            //2.返回错误
            return null;
        } else {
            //6.数据库中存在，写入redis
            stringRedisTemplate.opsForValue().set(keyPrefix+ id, JSONUtil.toJsonStr(r), time, unit);
            //7.返回对象信息
            return r;
        }
    }
    /**
     * 逻辑过期解决缓存击穿逻辑
     * @param id
     * @return
     */
    //创建线程池
    private static final ExecutorService executorService = Executors.newFixedThreadPool(10);

    public <R,ID> R queryWithLogicalExpire(String keyPrefix,ID id, Class<R> type, Function<ID,R> dbFallback, Long time, TimeUnit unit) {
        //1.在redis中查询对象信息
        String s = stringRedisTemplate.opsForValue().get(keyPrefix + id);
        //2.判断对象是否存在
        if (StrUtil.isBlank(s)) {
            //3.对象不存在，直接返回空值
            return null;
        }
        //4.命中，将json数据反序列化为对象
        RedisData data = JSONUtil.toBean(s, RedisData.class);
        JSONObject json = (JSONObject) data.getData();
        R r1 = JSONUtil.toBean(json, type);
        //5.判断是否过期
        if (data.getExpireTime().isAfter(LocalDateTime.now())) {
            //6.未过期，直接返回对象
            return r1;
        }
        //6。过期，尝试获取互斥锁
        boolean isLock = tryLock(RedisConstants.LOCK_SHOP_KEY + id);
        //7.判断是否获取成功
        if (isLock) {
            //获取互斥锁成功，开启独立线程，实现缓存重建
            executorService.submit(() -> {
                try {
                    //查询数据库
                    R r = dbFallback.apply(id);
                    //重建缓存
                    this.setWithLogicalExpire(keyPrefix, r, time, unit);
                    //释放锁
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }finally {
                    unLock(RedisConstants.LOCK_SHOP_KEY + id);
                }
            });
        }
        //8.如果获取失败，说明没有其他线程正在写入，可以返回数据
        return r1;
    }
    /**
     * 尝试获取锁
     * @param key
     * @return
     */
    private boolean tryLock(String key) {
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }

    /**
     * 解锁
     * @param key
     */
    private void unLock(String key) {
        stringRedisTemplate.delete(key);
    }
}
